package handler

import (
	"context"
	"user/domain/model"
	"user/domain/service"
	pb "user/proto"
)

type User struct {
	UserService service.IUserService
}

func (u *User) Register(
	ctx context.Context,
	userRegisterRequest *pb.UserRegisterRequest,
	userRegisterResponse *pb.UserRegisterResponse) error {
	userRegister := &model.User{
		Username: userRegisterRequest.Username,
		Name:     userRegisterRequest.Name,
		Password: userRegisterRequest.Password,
	}
	_, err := u.UserService.AddUser(userRegister)
	if err != nil {
		return err
	}
	userRegisterResponse.Code = 200
	userRegisterResponse.Msg = "注册成功"
	return nil
}

func (u *User) Login(
	ctx context.Context,
	userLoginRequest *pb.UserLoginRequest,
	userLoginResponse *pb.UserLoginResponse) error {
	_, err := u.UserService.CheckPwd(userLoginRequest.Username, userLoginRequest.Password)
	if err != nil {
		return err
	}
	userLoginResponse.Code = 200
	userLoginResponse.Msg = "登录成功"
	return nil
}

func (u *User) GetUserInfo(
	ctx context.Context,
	userInfoRequest *pb.UserInfoRequest,
	userInfoResponse *pb.UserInfoResponse) error {
	userInfo, err := u.UserService.FindUserByName(userInfoRequest.Username)
	if err != nil {
		return err
	}
	userInfoResponse.Name = userInfo.Name
	userInfoResponse.UserID = userInfo.ID
	userInfoResponse.Username = userInfo.Username
	return nil
}
